<!-- MyBuying.vue - 我的购买（订单列表）-->
<template>
  <div class="my-buying-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon class="header-icon"><ShoppingBag /></el-icon>
        <div>
          <h2 class="header-title">我的订单</h2>
          <p class="header-subtitle">共 {{ orders.length }} 个订单</p>
        </div>
      </div>
      <div class="header-right">
        <el-button 
          type="warning" 
          :icon="Delete" 
          @click="cleanInvalidData"
          :loading="loading"
        >
          清理无效数据
        </el-button>
        <el-button 
          type="primary" 
          :icon="RefreshRight" 
          @click="forceRefresh"
          :loading="loading"
        >
          强制刷新
        </el-button>
      </div>
    </div>

    <!-- 状态筛选 -->
    <div class="status-tabs">
      <div 
        class="tab-item" 
        :class="{ active: selectedStatus === null }"
        @click="selectedStatus = null"
      >
        <span class="tab-label">全部</span>
        <span class="tab-count">{{ orders.length }}</span>
      </div>
      <div 
        class="tab-item"
        :class="{ active: selectedStatus === status.value }"
        v-for="status in statusList"
        :key="status.value"
        @click="selectedStatus = status.value"
      >
        <el-icon :class="`icon-${status.type}`">
          <component :is="status.icon" />
        </el-icon>
        <span class="tab-label">{{ status.label }}</span>
        <span class="tab-count">{{ getStatusCount(status.value) }}</span>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton v-for="i in 3" :key="i" :rows="3" animated class="loading-card" />
    </div>

    <!-- 空状态 -->
    <div v-else-if="filteredOrders.length === 0" class="empty-state">
      <el-empty :description="selectedStatus === null ? '还没有订单' : '暂无该状态的订单'">
        <el-button type="primary" @click="$router.push('/gear/market')">
          去渔具市场逛逛
        </el-button>
      </el-empty>
    </div>

    <!-- 订单列表 -->
    <div v-else class="orders-list">
      <el-card 
        v-for="order in filteredOrders"
        :key="order.orderId"
        class="order-card"
        shadow="hover"
      >
        <!-- 订单头部 -->
        <div class="order-header">
          <div class="order-no">
            <span class="label">订单号：</span>
            <span class="value">{{ order.code }}</span>
            <el-button 
              text 
              size="small" 
              @click="copyOrderNo(order.code)"
              class="copy-btn"
            >
              <el-icon><DocumentCopy /></el-icon>
            </el-button>
          </div>
          <el-tag :type="getStatusType(order.status)" size="large">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>

        <!-- 订单内容 -->
        <div class="order-content" @click="viewOrderDetail(order.id)">
          <div class="product-image">
            <el-image :src="getImageUrl(order.coverList)" fit="cover">
              <template #error>
                <div class="image-error">
                  <el-icon><PictureFilled /></el-icon>
                </div>
              </template>
            </el-image>
          </div>

          <div class="product-info">
            <h3 class="product-name">{{ order.productName }}</h3>
            <p class="product-meta">数量：{{ order.quantity }}</p>
            <p class="product-meta" v-if="order.oldLevel">新旧程度：{{ order.oldLevel }}成新</p>
            <div class="product-price">
              <span class="label">实付款：</span>
              <span class="price">¥{{ order.totalAmount }}</span>
            </div>
          </div>

          <div class="order-info">
            <p class="order-time">
              <el-icon><Clock /></el-icon>
              {{ formatDate(order.createTime) }}
            </p>
          </div>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions">
          <el-button size="small" @click="viewOrderDetail(order.id)">
            订单详情
          </el-button>
          
          <!-- 待支付：可取消、付款 -->
          <template v-if="order.status === 'pending'">
            <el-button size="small" type="danger" plain @click="handleCancelOrder(order)">
            取消订单
          </el-button>
            <el-button size="small" type="primary" @click="handlePayOrder(order)">
              立即支付
            </el-button>
          </template>

          <!-- 已发货：可确认收货 -->
          <template v-if="order.status === 'shipped'">
            <el-button size="small" type="success" @click="handleConfirmOrder(order)">
              确认收货
            </el-button>
          </template>

          <!-- 已完成：无操作按钮 -->
          <template v-if="order.status === 'delivered'">
            <!-- 已收货订单无需操作按钮 -->
          </template>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI, userAPI } from '@/api'
import {
  ShoppingBag,
  Clock,
  Wallet,
  Van,
  CircleCheck,
  WarningFilled,
  DocumentCopy,
  PictureFilled,
  RefreshRight,
  Delete
} from '@element-plus/icons-vue'

const router = useRouter()

// 数据
const orders = ref([])
const loading = ref(false)
const selectedStatus = ref(null)

// 状态列表
const statusList = [
  { value: 'pending', label: '待支付', icon: 'Clock', type: 'warning' },
  { value: 'paid', label: '已支付', icon: 'Wallet', type: 'info' },
  { value: 'shipped', label: '已发货', icon: 'Van', type: 'primary' },
  { value: 'delivered', label: '已收货', icon: 'CircleCheck', type: 'success' },
  { value: 'cancelled', label: '已取消', icon: 'WarningFilled', type: 'info' }
]

// 过滤后的订单
const filteredOrders = computed(() => {
  if (selectedStatus.value === null) {
    return orders.value
  }
  return orders.value.filter(order => order.status === selectedStatus.value)
})

// 获取订单列表
// 获取用户信息
const getUserInfo = async (userId) => {
  try {
    const response = await userAPI.getUserInfoById(userId);
    if (response.code === 0) {
      return {
        userId: response.data.userId,
        username: response.data.username,
        nickName: response.data.nickName,
        displayName: response.data.displayName
      };
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
  
  // 返回默认值
  return {
    userId: userId,
    username: `用户${userId}`,
    nickName: null,
    displayName: `用户${userId}`
  };
};

// 验证订单在数据库中是否真实存在
const validateOrdersInDatabase = async () => {
  console.log('MyBuying: 开始验证订单在数据库中的存在性')
  
  const validOrders = []
  const invalidOrders = []
  
  for (const order of orders.value) {
    try {
      // 调用订单详情API验证订单是否存在
      console.log(`MyBuying: 验证订单 ${order.id} 是否存在...`)
      const response = await orderAPI.getOrderDetail(order.id)
      
      if (response.code === 0 && response.data) {
        console.log(`MyBuying: 订单 ${order.id} 在数据库中存在`)
        validOrders.push(order)
      } else {
        console.warn(`MyBuying: 订单 ${order.id} 在数据库中不存在，已过滤`)
        invalidOrders.push(order)
      }
    } catch (error) {
      console.warn(`MyBuying: 验证订单 ${order.id} 时出错:`, error)
      // 如果API调用失败，也认为订单不存在
      invalidOrders.push(order)
    }
  }
  
  console.log(`MyBuying: 验证完成 - 有效订单: ${validOrders.length}, 无效订单: ${invalidOrders.length}`)
  
  if (invalidOrders.length > 0) {
    console.warn('MyBuying: 发现无效订单，已自动过滤:', invalidOrders)
    ElMessage.warning(`发现 ${invalidOrders.length} 个无效订单，已自动过滤`)
  }
  
  // 更新订单列表，只保留有效的订单
  orders.value = validOrders
}

// 清理无效数据
const cleanInvalidData = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将清理所有无效的订单数据，包括数据库中不存在的订单。确定要继续吗？',
      '清理无效数据',
      {
        confirmButtonText: '确定清理',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    console.log('MyBuying: 开始清理无效数据')
    loading.value = true
    
    // 验证并清理无效订单
    await validateOrdersInDatabase()
    
    ElMessage.success('无效数据清理完成')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理无效数据失败:', error)
      ElMessage.error('清理无效数据失败')
    }
  } finally {
    loading.value = false
  }
}

// 强制刷新订单数据
const forceRefresh = async () => {
  console.log('MyBuying: 强制刷新订单数据')
  
  // 清除所有可能的缓存
  try {
    // 清除localStorage中的相关数据
    const keysToRemove = []
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i)
      if (key && (key.includes('order') || key.includes('cart') || key.includes('favorite'))) {
        keysToRemove.push(key)
      }
    }
    keysToRemove.forEach(key => {
      console.log('MyBuying: 清除缓存:', key)
      localStorage.removeItem(key)
    })
    
    // 清除sessionStorage中的相关数据
    const sessionKeysToRemove = []
    for (let i = 0; i < sessionStorage.length; i++) {
      const key = sessionStorage.key(i)
      if (key && (key.includes('order') || key.includes('cart') || key.includes('favorite'))) {
        sessionKeysToRemove.push(key)
      }
    }
    sessionKeysToRemove.forEach(key => {
      console.log('MyBuying: 清除会话缓存:', key)
      sessionStorage.removeItem(key)
    })
    
    console.log('MyBuying: 缓存清理完成')
  } catch (error) {
    console.warn('MyBuying: 清理缓存时出错:', error)
  }
  
  // 清空当前数据
  orders.value = []
  // 重新获取数据
  await fetchOrders()
}

const fetchOrders = async () => {
  try {
    loading.value = true
    console.log('MyBuying: 开始获取订单数据...')
    const response = await orderAPI.getMyOrders()
    console.log('MyBuying: API响应:', response)
    
    if (response.code === 0) {
      orders.value = response.data || []
      console.log('MyBuying: 获取到的订单数据:', orders.value)
      console.log('MyBuying: 订单总数:', orders.value.length)
      console.log('MyBuying: 原始API数据:', JSON.stringify(response.data, null, 2))
      
      // 详细记录每个订单的信息
      orders.value.forEach((order, index) => {
        console.log(`MyBuying: 订单${index + 1}:`, {
          id: order.id,
          code: order.code,
          status: order.status,
          productId: order.productId,
          productName: order.productName,
          totalAmount: order.totalAmount
        })
      })
      
      // 过滤掉无效的订单（没有ID或状态异常的订单）
      orders.value = orders.value.filter(order => {
        const isValid = order && order.id && order.status
        if (!isValid) {
          console.warn('MyBuying: 发现无效订单，已过滤:', order)
        }
        return isValid
      })
      
      // 验证订单数据的完整性
      orders.value = orders.value.filter(order => {
        // 检查订单是否有必要的字段
        const hasRequiredFields = order.id && order.status && order.productId
        if (!hasRequiredFields) {
          console.warn('MyBuying: 订单缺少必要字段，已过滤:', {
            id: order.id,
            status: order.status,
            productId: order.productId,
            fullOrder: order
          })
          return false
        }
        
        // 检查订单状态是否有效
        const validStatuses = ['pending', 'paid', 'shipped', 'delivered', 'cancelled']
        const hasValidStatus = validStatuses.includes(order.status)
        if (!hasValidStatus) {
          console.warn('MyBuying: 订单状态无效，已过滤:', {
            id: order.id,
            status: order.status,
            fullOrder: order
          })
          return false
        }
        
        return true
      })
      
      // 验证订单在数据库中是否真实存在（仅在强制刷新时执行）
      if (orders.value.length > 0) {
        console.log('MyBuying: 检测到订单数据，开始验证数据库存在性')
        await validateOrdersInDatabase()
      }
      
      // 为每个订单补充缺失的数据
      for (const order of orders.value) {
        // 补充默认值
        if (!order.code && order.id) {
          order.code = `ORD${order.id.toString().padStart(6, '0')}`
        }
        if (!order.totalAmount && order.buyPrice) {
          order.totalAmount = order.buyPrice
        }
        // 如果还是没有总金额，使用商品价格
        if (!order.totalAmount && order.price) {
          order.totalAmount = order.price
        }
        if (!order.quantity) {
          order.quantity = 1
        }
        
        // 确保订单状态有默认值
        if (!order.status) {
          order.status = 'pending'
        }
        
        console.log(`MyBuying: 订单 ${order.id} 状态: ${order.status}`)
        console.log(`MyBuying: 订单 ${order.id} 商品信息:`, {
          productName: order.productName,
          price: order.price,
          coverList: order.coverList,
          oldLevel: order.oldLevel
        });
        
        // 为每个订单获取卖家用户信息
        if (order.sellerId) {
          const userInfo = await getUserInfo(order.sellerId);
          order.sellerUsername = userInfo.username;
          order.sellerNickName = userInfo.nickName;
          order.sellerDisplayName = userInfo.displayName;
        }
      }
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      console.warn('MyBuying: 用户未授权，可能是token过期')
      // 不显示错误消息，因为request.js已经处理了token清除
      // 用户会被路由守卫重定向到登录页
    } else {
      ElMessage.error('获取订单失败')
    }
  } finally {
    loading.value = false
  }
}

// 取消订单
const handleCancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单【${order.code}】吗？`,
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    console.log('MyBuying: 开始取消订单:', order.id)
    const response = await orderAPI.cancelOrder(order.id)
    console.log('MyBuying: 取消订单响应:', response)
    
    if (response.code === 0) {
      ElMessage.success('订单已取消')
      order.status = 'cancelled'
      
      // 触发全局事件，通知商品详情页面刷新状态
      window.dispatchEvent(new CustomEvent('orderCancelled', {
        detail: { productId: order.productId }
      }))
    } else {
      ElMessage.error(response.message || '取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 付款
const handlePayOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认支付订单【${order.code}】吗？\n支付金额：¥${order.totalAmount}`,
      '确认支付',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    console.log('MyBuying: 开始支付订单:', order.id)
    const response = await orderAPI.payOrder(order.id)
    console.log('MyBuying: 支付响应:', response)
    
    if (response.code === 0) {
      ElMessage.success('支付成功！')
      order.status = 'paid'
      
      // 触发全局事件，通知相关页面刷新
      window.dispatchEvent(new CustomEvent('orderStatusChanged', {
        detail: { orderId: order.id, newStatus: 'paid' }
      }))
      
      // 刷新订单列表
      fetchOrders()
    } else {
      ElMessage.error(response.message || '支付失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      console.log('MyBuying: 用户取消支付')
    } else {
      console.error('支付失败:', error)
      ElMessage.error('支付失败')
    }
  }
}

// 确认收货
const handleConfirmOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认已收到订单【${order.code}】的商品吗？`,
      '确认收货',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    console.log('MyBuying: 开始确认收货:', order.id)
    const response = await orderAPI.confirmOrder(order.id)
    console.log('MyBuying: 确认收货响应:', response)
    
    if (response.code === 0) {
      ElMessage.success('确认收货成功')
      order.status = 'delivered'
      
      // 触发全局事件，通知相关页面更新
      window.dispatchEvent(new CustomEvent('orderStatusChanged', {
        detail: { orderId: order.id, status: 'delivered' }
      }))
    } else {
      ElMessage.error(response.message || '确认收货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  }
}

// 再次购买功能已移除

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/gear/order/${orderId}`)
}

// 复制订单号
const copyOrderNo = (orderNo) => {
  navigator.clipboard.writeText(orderNo)
  ElMessage.success('订单号已复制')
}

// 工具函数
const getStatusCount = (status) => {
  return orders.value.filter(order => order.status === status).length
}

const getStatusText = (status) => {
  const map = { 
    'pending': '待支付', 
    'paid': '已支付', 
    'shipped': '已发货', 
    'delivered': '已收货', 
    'cancelled': '已取消' 
  }
  return map[status] || '未知'
}

const getStatusType = (status) => {
  const map = { 
    'pending': 'warning', 
    'paid': 'info', 
    'shipped': 'primary', 
    'delivered': 'success', 
    'cancelled': 'info' 
  }
  return map[status] || 'info'
}

const getImageUrl = (coverList) => {
  if (!coverList) return ''
  try {
    const list = typeof coverList === 'string' ? JSON.parse(coverList) : coverList
    return Array.isArray(list) ? list[0] : list
  } catch {
    return coverList
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped lang="scss">
$primary-color: #409eff;
$danger-color: #f56c6c;
$warning-color: #e6a23c;
$success-color: #67c23a;

.my-buying-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .header-icon {
    font-size: 36px;
  }

  .header-title {
    font-size: 28px;
    margin: 0;
    font-weight: 600;
  }

  .header-subtitle {
    margin: 5px 0 0 0;
    font-size: 14px;
    opacity: 0.9;
  }
}

.status-tabs {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  .tab-item {
    flex: 1;
    min-width: 120px;
    padding: 15px 20px;
    border-radius: 8px;
    background: #f5f7fa;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;

    &:hover {
      background: #e8f4ff;
      transform: translateY(-2px);
    }

    &.active {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }

    .el-icon {
      font-size: 24px;

      &.icon-warning { color: #e6a23c; }
      &.icon-info { color: #909399; }
      &.icon-primary { color: #409eff; }
      &.icon-success { color: #67c23a; }
    }

    .tab-label {
      font-size: 14px;
      font-weight: 500;
    }

    .tab-count {
      font-size: 18px;
      font-weight: 700;
    }

    &.active {
      .el-icon {
        color: white !important;
      }
    }
  }
}

.loading-container {
  .loading-card {
    background: white;
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 15px;
  }
}

.empty-state {
  background: white;
  border-radius: 12px;
  padding: 80px 20px;
  text-align: center;
}

.orders-list {
  .order-card {
    margin-bottom: 15px;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
    }
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;

  .order-no {
    display: flex;
    align-items: center;
    gap: 10px;

    .label {
      font-size: 14px;
      color: #909399;
    }

    .value {
      font-size: 14px;
      color: #303133;
      font-family: monospace;
    }

    .copy-btn {
      padding: 0 8px;
    }
  }
}

.order-content {
  display: flex;
  gap: 20px;
  padding: 10px 0;
  cursor: pointer;

  .product-image {
    width: 100px;
    height: 100px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;

    .image-error {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f7fa;
      color: #909399;
      font-size: 32px;
    }
  }

  .product-info {
    flex: 1;

    .product-name {
      font-size: 16px;
      margin: 0 0 10px 0;
      color: #303133;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .product-meta {
      font-size: 14px;
      color: #909399;
      margin: 5px 0;
    }

    .product-price {
      margin-top: 10px;

      .label {
        font-size: 14px;
        color: #606266;
      }

      .price {
        font-size: 20px;
        color: $danger-color;
        font-weight: 700;
        margin-left: 5px;
      }
    }
  }

  .order-info {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-end;

    .order-time {
      font-size: 12px;
      color: #909399;
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }
}

.order-actions {
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .order-content {
    flex-direction: column;

    .order-info {
      align-items: flex-start;
    }
  }

  .status-tabs {
    .tab-item {
      flex: 1 1 calc(50% - 10px);
    }
  }
}
</style>
